<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/myblogs/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/myblogs/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/myblogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/myblogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/myblogs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/myblogs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/myblogs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/myblogs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/myblogs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JTable," />





  <link rel="alternate" href="/myblogs/atom.xml" title="天行健の博客" type="application/atom+xml" />






<meta name="description" content="设置JTable双击表头自动排序12345&#x2F;&#x2F;定义排序器private TableRowSorter&lt;DefaultTableModel&gt; tableRowSorter &#x3D; new TableRowSorter&lt;&gt;(getDefaultTableModel());&#x2F;&#x2F;在创建表格方法中设置排序table.setRowSorter(tableRowSorter);   设置JT">
<meta property="og:type" content="article">
<meta property="og:title" content="Swing开发技巧——JTable篇">
<meta property="og:url" content="https://joy_24.gitee.io/2020/12/09/swing-jtable1/index.html">
<meta property="og:site_name" content="天行健の博客">
<meta property="og:description" content="设置JTable双击表头自动排序12345&#x2F;&#x2F;定义排序器private TableRowSorter&lt;DefaultTableModel&gt; tableRowSorter &#x3D; new TableRowSorter&lt;&gt;(getDefaultTableModel());&#x2F;&#x2F;在创建表格方法中设置排序table.setRowSorter(tableRowSorter);   设置JT">
<meta property="og:locale">
<meta property="article:published_time" content="2020-12-09T08:34:13.000Z">
<meta property="article:modified_time" content="2021-10-26T07:05:17.783Z">
<meta property="article:author" content="Joy Wang">
<meta property="article:tag" content="JTable">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://joy_24.gitee.io/2020/12/09/swing-jtable1/"/>





  <title>Swing开发技巧——JTable篇 | 天行健の博客</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a target="_blank" rel="noopener" href="https://github.com/JoyWJ" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>


    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/myblogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">天行健の博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个开发博客的初学者。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/myblogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/myblogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/myblogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/myblogs/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/myblogs/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/myblogs/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/12/09/swing-jtable1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Swing开发技巧——JTable篇</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-09T16:34:13+08:00">
                2020-12-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/Swing/" itemprop="url" rel="index">
                    <span itemprop="name">Swing</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  881
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  4
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="设置JTable双击表头自动排序"><a href="#设置JTable双击表头自动排序" class="headerlink" title="设置JTable双击表头自动排序"></a>设置JTable双击表头自动排序</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义排序器</span></span><br><span class="line"><span class="keyword">private</span> TableRowSorter&lt;DefaultTableModel&gt; tableRowSorter = <span class="keyword">new</span> TableRowSorter&lt;&gt;(getDefaultTableModel());</span><br><span class="line"></span><br><span class="line"><span class="comment">//在创建表格方法中设置排序</span></span><br><span class="line">table.setRowSorter(tableRowSorter);</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="设置JTable显示水平滚动条和垂直滚动条"><a href="#设置JTable显示水平滚动条和垂直滚动条" class="headerlink" title="设置JTable显示水平滚动条和垂直滚动条"></a>设置JTable显示水平滚动条和垂直滚动条</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">jScrollPane = <span class="keyword">new</span> JScrollPane(getTable())</span><br><span class="line"></span><br><span class="line"><span class="comment">//水平滚动条</span></span><br><span class="line">jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);</span><br><span class="line"></span><br><span class="line"><span class="comment">//垂直滚动条</span></span><br><span class="line">jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);</span><br><span class="line"></span><br><span class="line"><span class="comment">//同时需要对JScrollPane中的JTable设置属性</span></span><br><span class="line">table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); </span><br></pre></td></tr></table></figure>

<p>备注：</p>
<p>水平和垂直滚动条总是出现</p>
<p>JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS</p>
<p>JScrollPane.VERTICAL_SCROLLBAR_ALWAYS</p>
<p>水平和垂直滚动条自动出现</p>
<p>JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED</p>
<p>JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED</p>
<hr>
<h1 id="设置JTable表格内容自动换行"><a href="#设置JTable表格内容自动换行" class="headerlink" title="设置JTable表格内容自动换行"></a>设置JTable表格内容自动换行</h1><p>方式一：使用 JTextArea</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">JTable table = <span class="keyword">new</span> JTable();</span><br><span class="line"><span class="comment">//SystemProgramControlPanel为当前的类</span></span><br><span class="line">table.setDefaultRenderer(Object.class, <span class="keyword">new</span> SystemProgramControlPanel.TableViewRenderer());</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     *表格内容渲染，设置自动换行</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@author</span> Administrator</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TableViewRenderer</span> <span class="keyword">extends</span> <span class="title">JTextArea</span> <span class="keyword">implements</span> <span class="title">TableCellRenderer</span></span></span><br><span class="line"><span class="class">    </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">TableViewRenderer</span><span class="params">()</span></span>&#123;</span><br><span class="line">            setOpaque(<span class="keyword">false</span>);</span><br><span class="line">            setLineWrap(<span class="keyword">true</span>); <span class="comment">//利用JTextArea的自动换行方法</span></span><br><span class="line">            setWrapStyleWord(<span class="keyword">true</span>);</span><br><span class="line">            setFont(<span class="keyword">new</span> Font(<span class="string">&quot;宋体&quot;</span>, Font.BOLD, <span class="number">18</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> Component <span class="title">getTableCellRendererComponent</span><span class="params">(JTable table, Object value,</span></span></span><br><span class="line"><span class="function"><span class="params">                                         <span class="keyword">boolean</span> isSelected, <span class="keyword">boolean</span> hasFocus, <span class="keyword">int</span> row, <span class="keyword">int</span> column)</span> </span>&#123;</span><br><span class="line">            <span class="comment">//根据具体需求设置特殊行的颜色(此处和内容换行无关)</span></span><br><span class="line">            <span class="keyword">if</span>(row &gt;= <span class="number">0</span> &amp;&amp; getTable().getValueAt(row,<span class="number">6</span>) != <span class="keyword">null</span>)&#123;</span><br><span class="line">                <span class="keyword">if</span>(<span class="string">&quot;3&quot;</span>.equals(getTable().getValueAt(row,<span class="number">6</span>).toString()))&#123;</span><br><span class="line">                    setForeground(<span class="keyword">new</span> Color(<span class="number">222</span>, <span class="number">173</span>, <span class="number">171</span>, <span class="number">250</span>));</span><br><span class="line">                &#125;<span class="keyword">else</span> <span class="keyword">if</span>(<span class="string">&quot;4&quot;</span>.equals(getTable().getValueAt(row,<span class="number">6</span>).toString()))&#123;</span><br><span class="line">                    setForeground(<span class="keyword">new</span> Color(<span class="number">123</span>, <span class="number">222</span>, <span class="number">157</span>));</span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    setForeground(<span class="keyword">new</span> Color(<span class="number">255</span>, <span class="number">253</span>, <span class="number">254</span>, <span class="number">250</span>));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 计算当下行的最佳高度</span></span><br><span class="line">            <span class="keyword">int</span> maxPreferredHeight = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; table.getColumnCount(); i++) &#123;</span><br><span class="line">                setText(<span class="string">&quot;&quot;</span> + table.getValueAt(row, i));</span><br><span class="line">                setSize(table.getColumnModel().getColumn(column).getWidth(), <span class="number">0</span>);</span><br><span class="line">                maxPreferredHeight = Math.max(maxPreferredHeight, getPreferredSize().height);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (table.getRowHeight(row) != maxPreferredHeight)  <span class="comment">// 少了这行则处理器瞎忙</span></span><br><span class="line">                table.setRowHeight(row, maxPreferredHeight);</span><br><span class="line"></span><br><span class="line">            setText(value == <span class="keyword">null</span> ? <span class="string">&quot;&quot;</span> : value.toString());</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>



<p>方式二：使用 JLable </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyCellRenderer</span> <span class="keyword">extends</span> <span class="title">DefaultTableCellRenderer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">MyCellRenderer</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Component <span class="title">getTableCellRendererComponent</span><span class="params">(JTable table, Object value, <span class="keyword">boolean</span> isSelected, 												<span class="keyword">boolean</span> hasFocus, <span class="keyword">int</span> row, <span class="keyword">int</span> column)</span> </span>&#123;</span><br><span class="line">			<span class="comment">//此处通过拼接&lt;html&gt;并放到JLabel中实现内容换行，下面还要计算设置行高</span></span><br><span class="line">            String val = value!=<span class="keyword">null</span>?<span class="string">&quot;&lt;html&gt;&quot;</span>+value.toString()+<span class="string">&quot;&lt;/html&gt;&quot;</span> : <span class="string">&quot;&quot;</span>;</span><br><span class="line">            JLabel label = <span class="keyword">new</span> JLabel(val, JLabel.CENTER);</span><br><span class="line">            label.setFont(<span class="keyword">new</span> Font(<span class="string">&quot;宋体&quot;</span>, Font.BOLD, <span class="number">14</span>));</span><br><span class="line">            label.setForeground(Color.WHITE);</span><br><span class="line">            table.setEnabled(<span class="keyword">true</span>);</span><br><span class="line"><span class="comment">//            label.setBorder(BorderFactory.createLineBorder(Color.red));</span></span><br><span class="line">            <span class="keyword">if</span> (isSelected) &#123;</span><br><span class="line">                label.setOpaque(<span class="keyword">true</span>);</span><br><span class="line">                label.setBackground(getTable().getSelectionBackground());</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>(row &gt;= <span class="number">0</span> &amp;&amp; getTable().getValueAt(row,<span class="number">6</span>) != <span class="keyword">null</span>)&#123;</span><br><span class="line">                <span class="keyword">if</span>(<span class="string">&quot;3&quot;</span>.equals(getTable().getValueAt(row,<span class="number">6</span>).toString()))&#123;</span><br><span class="line">                    label.setForeground(<span class="keyword">new</span> Color(<span class="number">222</span>, <span class="number">173</span>, <span class="number">171</span>, <span class="number">250</span>));</span><br><span class="line">                &#125;<span class="keyword">else</span> <span class="keyword">if</span>(<span class="string">&quot;4&quot;</span>.equals(getTable().getValueAt(row,<span class="number">6</span>).toString()))&#123;</span><br><span class="line">                    label.setForeground(<span class="keyword">new</span> Color(<span class="number">123</span>, <span class="number">222</span>, <span class="number">157</span>));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 计算当下行的最佳高度</span></span><br><span class="line">            <span class="keyword">int</span> maxPreferredHeight = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">if</span>(column == <span class="number">5</span>)&#123;</span><br><span class="line">                <span class="keyword">double</span> width = label.getPreferredSize().getWidth();</span><br><span class="line">                <span class="keyword">int</span> rowHeight = (<span class="keyword">int</span>) (Math.ceil(width / <span class="number">500</span>) * <span class="number">30</span>);</span><br><span class="line">                maxPreferredHeight = Math.max(maxPreferredHeight, rowHeight);</span><br><span class="line">                table.setRowHeight(row, maxPreferredHeight);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> label;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="获得JTable中的选中行中的数据"><a href="#获得JTable中的选中行中的数据" class="headerlink" title="获得JTable中的选中行中的数据"></a>获得JTable中的选中行中的数据</h1><p>首先假设两个JTable，他们为table1与table2</p>
<p>假设从table1取值放到table2中</p>
<p>1、获得table1的选中行 int index = table1.getSelectedRow();</p>
<p>2、获得table1中列的个数 int column = table1.getColumnCount();</p>
<p>3、取出表格中index行中的值，用集合保存！</p>
<p>（1）创建一个保存的集合Vector&lt;Vector<Object>&gt; vector = Vector&lt;Vector<Object>&gt;();</Object></Object></p>
<p>（2） 再创建一个集合，用于加入到第一个集合 Vector<Object> object = Vector<Object>();</Object></Object></p>
<p>（3）将index行的所有数据取出放入第二个集合中 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> n= <span class="number">0</span>; n &lt; column; n ++)&#123;</span><br><span class="line">	object.add(table1.getVauleAt(index,n));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>（4）将第二集合中的数据加入到第一个集合中： vector.add(object);</p>
<p>4、创建table2的列名，并用一个集合表示，!</p>
<p>（1）创建一个集合，用于创建列名Vector<Object> object1 = new Vector<Object>();</Object></Object></p>
<p>（2） 为列名赋值，，，，在这里就省略了，具体的名视情况而定！</p>
<p>5、将取出的值加入到table2中：</p>
<p>（1）取得table2的模板DefaultTableModel model = (DefaultTableModel)table2.getModel();</p>
<p>（2）为模板添加内容：model.setDataVector(vector, object1)；</p>
<p>（3）将模板添加到table2中， table2.setModel(model);</p>
<p>大功告成！</p>

      
    </div>
    
    
    
    
    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Joy Wang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://joy_24.gitee.io/2020/12/09/swing-jtable1/" title="Swing开发技巧——JTable篇">https://joy_24.gitee.io/2020/12/09/swing-jtable1/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/myblogs/tags/JTable/" rel="tag"># JTable</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/myblogs/2020/11/27/javafx-1/" rel="next" title="JavaFX桌面应用开发-HelloWorld">
                <i class="fa fa-chevron-left"></i> JavaFX桌面应用开发-HelloWorld
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/myblogs/2020/12/09/swing-jtree/" rel="prev" title="Swing开发技巧——JTree篇">
                Swing开发技巧——JTree篇 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/myblogs/uploads/avatar.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                #<a href="/myblogs/archives%7C%7C%20archive">
                <a href="/myblogs/archives">
              
                  <span class="site-state-item-count">34</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/myblogs/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/myblogs/tags/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/myblogs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/joyWJ" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="wangjianjoy@126.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%AE%BE%E7%BD%AEJTable%E5%8F%8C%E5%87%BB%E8%A1%A8%E5%A4%B4%E8%87%AA%E5%8A%A8%E6%8E%92%E5%BA%8F"><span class="nav-number">1.</span> <span class="nav-text">设置JTable双击表头自动排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%AE%BE%E7%BD%AEJTable%E6%98%BE%E7%A4%BA%E6%B0%B4%E5%B9%B3%E6%BB%9A%E5%8A%A8%E6%9D%A1%E5%92%8C%E5%9E%82%E7%9B%B4%E6%BB%9A%E5%8A%A8%E6%9D%A1"><span class="nav-number">2.</span> <span class="nav-text">设置JTable显示水平滚动条和垂直滚动条</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%AE%BE%E7%BD%AEJTable%E8%A1%A8%E6%A0%BC%E5%86%85%E5%AE%B9%E8%87%AA%E5%8A%A8%E6%8D%A2%E8%A1%8C"><span class="nav-number">3.</span> <span class="nav-text">设置JTable表格内容自动换行</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%8E%B7%E5%BE%97JTable%E4%B8%AD%E7%9A%84%E9%80%89%E4%B8%AD%E8%A1%8C%E4%B8%AD%E7%9A%84%E6%95%B0%E6%8D%AE"><span class="nav-number">4.</span> <span class="nav-text">获得JTable中的选中行中的数据</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Joy Wang</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/myblogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/myblogs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblogs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/myblogs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/myblogs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/myblogs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/myblogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
